﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using System.Data.Services.Client;

namespace AzureTest
{
    public class TestDataSource
    {
        // _ServiceContext will hold the connection
        private TestDataServiceContext _ServiceContext = null;

        // Constructor gets appropriate config settings and opens a connection
        // If your table does not exist on the storage server it attempts to create it
        public TestDataSource()
        {
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            _ServiceContext = new TestDataServiceContext(storageAccount.TableEndpoint.ToString(), storageAccount.Credentials);
            
            // create table if it doesn't exist
            storageAccount.CreateCloudTableClient().CreateTableIfNotExist(TestDataServiceContext.DataTableName);
        }

        public IEnumerable<TestDataModel> Select()
        {
            var results = from c in _ServiceContext.DataTable
                          select c;

            var query = results.AsTableServiceQuery<TestDataModel>();
            var queryResults = query.Execute();

            return queryResults;
        }

        public void Delete(TestDataModel item)
        {
            _ServiceContext.AttachTo(TestDataServiceContext.DataTableName, item);
            _ServiceContext.DeleteObject(item);
            _ServiceContext.SaveChanges();
        }

        public void Insert(TestDataModel item)
        {
            _ServiceContext.AddObject(TestDataServiceContext.DataTableName, item);
            _ServiceContext.SaveChanges();
        }
    }
}